package cn.itsource.service.impl;

import cn.itsource.annotation.Log;
import cn.itsource.domain.Article;
import cn.itsource.dto.ArticleDto;
import cn.itsource.exception.BusinessException;
import cn.itsource.mapper.ArticleMapper;
import cn.itsource.query.ArticleQuery;
import cn.itsource.service.ArticleService;
import cn.itsource.util.AjaxResult;
import cn.itsource.util.BaiduAuditUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 业务实现类：文章Article
 */
@Service
@Transactional(propagation = Propagation.SUPPORTS,readOnly = true)
public class ArticleServiceImpl implements ArticleService {
    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private ArticleMapper articleMapper;

    @Override
    public List<Article> findAll() {
        return articleMapper.findAll();
    }

    @Override
    public Article findOne(Long id) {
        return articleMapper.findOne(id);
    }

    @Transactional
    @Override
    @Log
    public void add(Article article) { //
        if(!BaiduAuditUtils.TextCensor(article.getArticleName())){
            throw new BusinessException("文章名称不合法");
        }
        if(!BaiduAuditUtils.TextCensor(article.getArticleTag())){
            throw new BusinessException("文章标签不合法");
        }

        //添加到mysql数据库：添加到mysql数据之后才有id，但是_id是没有的
        articleMapper.add(article);
        //将数据添加到mongodb
        mongoTemplate.save(article);
    }

    @Transactional
    @Override
    @Log
    public void update(Article article) {
        if(!BaiduAuditUtils.TextCensor(article.getArticleName())){
            throw new BusinessException("文章名称不合法");
        }
        if(!BaiduAuditUtils.TextCensor(article.getArticleTag())){
            throw new BusinessException("文章标签不合法");
        }
        //修改mysql数据库
        article.setUpdateTime(new Date());
        articleMapper.update(article);

        //修改mongodb数据库
        //先根据id查整个对象【_id】
        Query query = new Query(Criteria.where("id").is(article.getId()));
        Article mongoDbArticle = mongoTemplate.findOne(query, Article.class);
        if(mongoDbArticle != null){
            article.set_id(mongoDbArticle.get_id());
        }
        //调用save方法去操作ongodb数据库
        mongoTemplate.save(article);
    }

    @Transactional
    @Override
    @Log
    public void delete(Long id) {
        //删除mysql数据
        articleMapper.delete(id);

        //删除mongodb的数据 - 按照添加删除
        Query query = new Query(Criteria.where("id").is(id));
        mongoTemplate.remove(query,Article.class);
    }

    @Override
    public PageInfo<Article> pageQuery(ArticleQuery query) {
       /* //查询总条数 - 原生分页的写法
        Integer totals = articleMapper.queryCount();
        //查询当前页的分页数据
        List<Article> list = articleMapper.queryData(query);*/
        //开启分页：1.首先查询总数量 2.根据驱动名使用相应的方式进行分页查询，如果是mysql，就会用limit 3.自动计算limit的第1个参数
        PageHelper.startPage(query.getCurrentPage(),query.getPageSize());
        List<Article> list = articleMapper.pageQuery(query);
        return new PageInfo<>(list);
    }

    @Override
    @Log
    public void patchDel(Long[] ids) {
        for (Long id : ids) {
            delete(id);
        }
    }

    @Override
    public List<ArticleDto> countByArticleType() {
        return articleMapper.countByArticleType();
    }

    @Override
    public List<ArticleDto> countByTime() {
        return articleMapper.countByTime();
    }

    @Override
    public List<Article> getDependencyArticle(Long id) {
        return articleMapper.getDependencyArticle(id);
    }

    @Override
    public List<ArticleDto> getChartColumn() {
        return articleMapper.getChartColumn();
    }

    @Override
    public List<ArticleDto> getChartPie() {
        return articleMapper.getChartPie();
    }

    @Override
    public AjaxResult readCount(Long id) {
        try {
            Article article = articleMapper.findOne(id);
            article.setArticleReadCount(article.getArticleReadCount() +1);
            articleMapper.update(article);
            return AjaxResult.me().setObj(article.getArticleReadCount());
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(false,"服务器异常");
        }
    }

    @Override
    public Map<String, Object> getArticleByType(Long typeId) {
        List<Article> articles = articleMapper.getArticleByType(typeId);
        Map<String, Object> map = new HashMap<>();
        if(articles.size() > 0){
            map.put("articles",articles);
            map.put("typeName",articles.get(0).getTypeName());
        }
        return map;
    }

}
